//
//  ANAroundController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/10.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANAroundController.h"
#import <CoreLocation/CoreLocation.h>
//#import "MainGoodsFilterView.h"
#import "AroundShopFilterView.h"
#import "MainSearchView.h"
#import "AroundShopCell.h"
#import "ShopEntity.h"
#import "ANShopInfoController.h"
#import "ANAppointmentPrepareController.h"

@interface ANAroundController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate,MainSearchViewDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, strong) MainSearchView *searchView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) AroundShopFilterView *filterView;

@property (nonatomic, strong) NSMutableArray<ShopEntity *> *dataSource;
@property (nonatomic) int pageNo;

@property (nonatomic, copy) NSString *searchText;

@property (nonatomic, copy) NSString *merchantType;

@property (nonatomic, copy) NSString *latitude;
@property (nonatomic, copy) NSString *longitude;

@end

@implementation ANAroundController

- (void)refreshLoad
{
    self.pageNo = 1;
    [self requestData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"周边门店";
    self.pageNo = 1;
    self.dataSource = @[].mutableCopy;
    self.searchText = @"";
    self.merchantType = @"";
    
    [self requestData];
    
    [self startLocation];
}

- (void)startLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [self.locationManager requestWhenInUseAuthorization];
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    }
}

/** 定位服务状态改变时调用*/
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户还未决定授权");
            break;
        }
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"访问受限");
            break;
        }
        case kCLAuthorizationStatusDenied:
        {
            // 类方法，判断是否开启定位服务
            if ([CLLocationManager locationServicesEnabled]) {
                NSLog(@"定位服务开启，被拒绝");
            } else {
                NSLog(@"定位服务关闭，不可用");
            }
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            NSLog(@"获得前后台授权");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            NSLog(@"获得前台授权");
            break;
        }
        default:
            break;
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations firstObject];
    CLLocationCoordinate2D coor = location.coordinate;
    self.latitude = [NSString stringWithFormat:@"%f",coor.latitude];
    self.longitude = [NSString stringWithFormat:@"%f",coor.longitude];
//    [self requestData];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error) {
            self.searchView.city = placemarks.firstObject.locality;
        }
    }];
}

- (void)requestData
{
    NSDictionary *para = @{
                           @"orgName":self.searchText,//商户名称 模糊查询
                           @"latitude":StringNone(self.latitude),
                           @"longitude":StringNone(self.longitude),
                           @"orderBy":@"",
                           @"merchantType":self.merchantType,
                           @"pageNo":@(self.pageNo),
                           @"pageSize":@20
                           };
    [URLManager.shareManager getUrlStr:Api_Around_Shop_List parameters:para entityClass:[ShopListEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                ShopListEntity *data = baseEntity.data;
                if (self.pageNo == 1) {
                    [self.dataSource removeAllObjects];
                    [self.tableView.mj_footer resetNoMoreData];
                    [self.tableView.mj_header endRefreshing];
                    if (data.data.count < 20) {
                        self.tableView.mj_footer.alpha = 0;
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    if (data.data.count == 0) {
                        [self showEmptyView];
                    }
                    else {
                        [self removeEmptyView];
                    }
                }
                else {
                    if (data.data.count < 20) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    else {
                        [self.tableView.mj_footer endRefreshing];
                    }
                }
                [self.dataSource addObjectsFromArray:data.data];
                [self.tableView reloadData];
            }
            else {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
        }
        else {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

- (void)setupSubViews
{
    self.searchView = [[MainSearchView alloc] init];
    self.searchView.delegate = self;
    [self.view addSubview:self.searchView];
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.equalTo(@44);
    }];
    WeakSelf
    self.searchView.searchHandler = ^(NSString * _Nonnull text) {
        weakSelf.searchText = text;
        weakSelf.pageNo = 1;
        [weakSelf requestData];
    };
    
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[AroundShopCell class] forCellReuseIdentifier:@"AroundShopCell"];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.searchView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    self.filterView = [[AroundShopFilterView alloc] init];
    self.filterView.filterHandler = ^(NSString * _Nonnull type) {
        weakSelf.merchantType = type;
        weakSelf.pageNo = 1;
        [weakSelf requestData];
    };
}

#pragma mark - MainSearchViewDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.searchText = searchText;
    self.pageNo = 1;
    [self requestData];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AroundShopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AroundShopCell" forIndexPath:indexPath];
    WeakSelf
    cell.appointmentHandler = ^{
        if (UserUtils.shared.isLogin) {
            //预约
            ANAppointmentPrepareController *vc = [[ANAppointmentPrepareController alloc] init];
            vc.shopEntity = weakSelf.dataSource[indexPath.row];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else {
            [UserUtils showLoginVc];
        }
        
    };
    cell.shopEntity = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ANShopInfoController *vc = [[ANShopInfoController alloc] init];
    vc.orgId = self.dataSource[indexPath.row].orgId;
    [self.navigationController pushViewController:vc animated:YES];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return kWidth(140);
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return self.filterView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 120;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, kTabBarHeight, 0);
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.pageNo = 1;
            [weakSelf requestData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            weakSelf.pageNo++;
            [weakSelf requestData];
        }];;
    }
    return _tableView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
